package cn.com.bluemoon.daps.system.controller;

import cn.com.bluemoon.daps.common.datascope.BmPermission;
import cn.com.bluemoon.daps.common.domain.BaseModel;
import cn.com.bluemoon.daps.common.domain.ResultBean;
import cn.com.bluemoon.daps.common.enums.BmStatus;
import cn.com.bluemoon.daps.common.exception.DapThrowException;
import cn.com.bluemoon.daps.common.mp.IBmService;
import cn.com.bluemoon.daps.system.entity.DapDataModelNameRecommendation;
import cn.com.bluemoon.daps.system.service.DapDataModelNameRecommendationService;
import cn.com.bluemoon.daps.system.vo.ModelNameRecommendSearchVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.util.function.Tuple2;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@Api(tags = "命名推荐")
@RestController
@Slf4j
@RequestMapping("/recommend")
public class NameRecommendController {

    @Autowired
    DapDataModelNameRecommendationService dapDataModelNameRecommendationService;

    @BmPermission(value = "model:table:modify", name = "命名推荐")
    @PostMapping("/modelTable/field/nameRecommend")
    @ApiOperation("模型表字段中命名推荐")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public ResultBean<?> nameRecommend(@RequestBody ModelNameRecommendSearchVo<DapDataModelNameRecommendation> searchVo) {
        Tuple2<BaseModel<DapDataModelNameRecommendation>, IPage<DapDataModelNameRecommendation>> resultTuples = dapDataModelNameRecommendationService.nameRecommend(searchVo);
        return IBmService.toAntDvPageTool(resultTuples.getT2()).addMoreData("recommendTerm", resultTuples.getT1());
    }

    @BmPermission(value = "system:nameRecommend:list", name = "列表查询")
    @PostMapping("/nameRecommend/List")
    @ApiOperation("命名推荐字段列表")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public ResultBean<?> nameRecommendList(@RequestBody ModelNameRecommendSearchVo<DapDataModelNameRecommendation> vo) {

        IPage<DapDataModelNameRecommendation> page = dapDataModelNameRecommendationService.nameRecommendList(vo);
        return ResultBean.ok(page);
    }

    @BmPermission(value = "system:nameRecommend:edit", name = "编辑")
    @PostMapping("/add/nameRecommend")
    @ApiOperation("新增或修改推荐词")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public ResultBean<?> addNameRecommend(@RequestBody @Valid DapDataModelNameRecommendation name) {

        // 查询库中有无相同的推荐词
        DapDataModelNameRecommendation recommendation = dapDataModelNameRecommendationService.getBaseMapper()
                .selectOne(new LambdaQueryWrapper<DapDataModelNameRecommendation>()
                .eq(DapDataModelNameRecommendation::getChinName, name.getChinName())
                .eq(DapDataModelNameRecommendation::getBmStatus, BmStatus.ON.getCode()));
        if(recommendation == null || recommendation.getId().equals(name.getId())){
            return ResultBean.ok(dapDataModelNameRecommendationService.saveOrUpdate(name));
        }else {
            return ResultBean.error("推荐词 :" + name.getChinName() + "重复");
        }
    }

    @BmPermission(value = "system:nameRecommend:info", name = "详情")
    @GetMapping("/nameRecommend/info")
    @ApiOperation("查看推荐词")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = DapDataModelNameRecommendation.class)})
    public ResultBean<?> nameRecommendInfo(@RequestParam("id") String id) {
        DapDataModelNameRecommendation recommendation = dapDataModelNameRecommendationService.getBaseMapper().selectById(id);
        return ResultBean.ok(recommendation);
    }


    @BmPermission(value = "system:nameRecommend:delete", name = "删除")
    @DeleteMapping("/del/nameRecommend")
    @ApiOperation("删除推荐词(批量)")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public ResultBean<?> delNameRecommend(@RequestBody List<String> ids) {
        return ResultBean.ok(dapDataModelNameRecommendationService.getBaseMapper().deleteBatchIds(ids));
    }

    @BmPermission(value = "system:nameRecommend:import", name = "导入", queryTokenPerm = true)
    @PostMapping("/import/nameRecommend")
    @ApiOperation("命名推荐导入")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = List.class)})
    public ResultBean<?> NameRecommendImport(@RequestParam MultipartFile mFile) {

        ResultBean<?> resultBean = dapDataModelNameRecommendationService.importExcel(mFile);
        return resultBean;
    }

    @BmPermission(value = "system:nameRecommend:download", name = "下载", queryTokenPerm = true)
    @GetMapping("/download")
    @ApiOperation("下载模板")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "ok", response = ResultBean.class)})
    public void download(HttpServletResponse response) {
        try {
            InputStream fis = this.getClass().getClassLoader().getResourceAsStream("download/命名推荐导入模板.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            response.setContentType("application/binary;charset=ISO8859-1");
            String fileName = URLEncoder.encode("命名推荐导入模板", "UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
            ServletOutputStream out = null;
            out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException e) {
            throw new DapThrowException("获取数据失败," + e.getMessage());
        } finally {
            //关闭文件输出流
        }
    }
}
